import { createRouter, createWebHistory } from 'vue-router'

import { whoami, setLogged, getLogged } from '../api/user'

const routes = [
    {
        path: '/',
        name: 'login',
        component: () => import('@/views/login.vue'),
    },
    {
        path: '/register',
        name: 'register',
        component: () => import('@/views/register.vue'),
    },
    {
        path: '/network-error',
        name: 'network-error',
        component: () => import('@/views/errors/network-error.vue'),
    },
    {
        path: '/home',
        name: 'home',
        component: () => import('@/views/home.vue'),
        children: [
            {
                path: 'index',
                name: 'index',
                component: () => import('@/views/index.vue'),
            },
            {
                path: 'plant-manager',
                name: 'plant-manager',
                component: () => import('@/views/plant-manager.vue'),
            },
            {
                path: 'zombie-manager',
                name: 'zombie-manager',
                component: () => import('@/views/zombie-manager.vue')
            },
            {
                path: 'admin-user-manager',
                name: 'admin-user',
                component: () => import('@/views/admin-user-manager.vue')
            },
            {
                path: 'common-user-manager',
                name: 'common-user',
                component: () => import('@/views/common-user-manager.vue')
            },
            {
                path: 'about',
                name: 'about',
                component: () =>
                    import('@/views/about.vue'),
            }
        ]
    },
]

const router = createRouter({
    routes,
    history: createWebHistory()
})

const whiteList = ['login', 'register', 'network-error']

router.beforeEach(async (to, from) => {
    // 如果当前路由在白名单, 那就直接跳转
    if (whiteList.find(it => it === to.name)) return true
    try {
        const logged = await getLogged(true)
        // 如果 暂未登录
        if (!logged && to.name != 'login') {
            if (logged) return true
            return {
                name: 'login'
            }
        }
    } catch (e) {
        return {
            name: 'network-error'
        }
    }
})

export default router